using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Betfair.Api;
using Bull.Core;

namespace Bull.Plugins.Market.ViewModels {
    public sealed class MarketBookViewModel : ViewModelBase {
        public string Description { get; private set; }
        public ReadOnlyCollection<RunnerViewModel> Runners { get; private set; }
        private IDictionary<long, RunnerViewModel> _runners;
        public MarketBookViewModel(MarketCatalogue marketCatalogue, MarketBook marketBook) {
            Description = marketCatalogue.Event.Name;
            var runners = marketBook.Runners.GroupBy(runner => runner.Id).ToDictionary(item => item.Key, item => item.FirstOrDefault());
            Runners = new ReadOnlyCollection<RunnerViewModel>(marketCatalogue.Runners.OrderBy(item => item.SortPriority).Select(runner => new RunnerViewModel(runner, runners[runner.Id].ExchangePrice)).ToList());
            _runners = Runners.GroupBy(item => item.Id).ToDictionary(item => item.Key, item => item.FirstOrDefault());
        }
    }

    public sealed class RunnerViewModel : ViewModelBase {
        public long Id { get; private set; }
        public string Name { get; private set; }
        public ReadOnlyCollection<QuoteViewModel> Back { get; private set; }
        public ReadOnlyCollection<QuoteViewModel> Lay { get; private set; }

        public RunnerViewModel(RunnerCatalogue runnerCatalogue, ExchangePrice exchangePrice) {
            Id = runnerCatalogue.Id;
            Name = runnerCatalogue.Name;
            Back = new ReadOnlyCollection<QuoteViewModel>(exchangePrice.Back.Select(back => new QuoteViewModel(back)).ToList());
            Lay = new ReadOnlyCollection<QuoteViewModel>(exchangePrice.Lay.OrderByDescending(item => item.Price).Select(back => new QuoteViewModel(back)).ToList());
        }
    }

    public sealed class QuoteViewModel : ViewModelBase {
        public double Price { get; private set; }
        public double Size { get; private set; }

        public QuoteViewModel(PriceSize priceSize) {
            Price = priceSize.Price;
            Size = priceSize.Size;
        }
    }
}